package cc.miwuya.property.service.impl;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.property.client.PropertyClient;
import cc.miwuya.property.client.ResidentialClient;
import cc.miwuya.property.domain.Shops;
import cc.miwuya.property.mapper.ShopsMapper;
import cc.miwuya.property.service.ShopsService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 杩烽浘妫灄
 * @description 针对表【shops】的数据库操作Service实现
 * @createDate 2024-02-22 19:49:08
 */
@Service
public class ShopsServiceImpl extends ServiceImpl<ShopsMapper, Shops>
        implements ShopsService {
    @Resource
    HttpServletRequest httpServletRequest;
    @Resource
    PropertyClient propertyClient;
    @Resource
    ResidentialClient residentialClient;

    @Override
    public Object getAllShops(Page page, String name) {
        Page<Shops> shopsPage = null;
        if (StrUtil.isEmpty(name)||name.equals("null")){
            Long propertyId = propertyClient.getPropertyByUserid(getCurrent());
            List<Long> residentialIdByPropertyId = residentialClient.getResidentialIdByPropertyId(propertyId);
            shopsPage = page(page, new QueryWrapper<Shops>().in("residential_id", residentialIdByPropertyId));
        }else {
            shopsPage = page(page, new QueryWrapper<Shops>().eq("residential_id", name));
        }

        //shopsService.list(new QueryWrapper<Shops>().in("residential_id", residentialIdByPropertyId));
        return shopsPage;
    }

    @Override
    public Object getOwnerList(Page page, Long ownerId, String name) {
        Page<Shops> shopsPage;
        if (StrUtil.isEmpty(name)||name.equals("null")){
            shopsPage = page(page, new QueryWrapper<Shops>().eq("user_id", ownerId));
        }else {
            shopsPage = page(page,new QueryWrapper<Shops>().eq("user_id", ownerId).like("name", name));
        }

        return shopsPage;
    }

    /**
     * 获取当前登录人的身份
     */
    public Long getCurrent() {
        String authorization = httpServletRequest.getHeader("Authorization");
        Claims claim = JwtUtils.getClaimByToken(authorization, "community");
        JSON parse = JSONUtil.parse(claim);
        Long username = Long.parseLong(parse.getByPath("userId").toString());
        return username;
    }
}




